import { Component, OnInit } from '@angular/core';
import {MatSnackBar} from '@angular/material';
import {ActivatedRoute, Router} from '@angular/router';
import {CustomerService} from '../shared/customer.service';
import {CustomerToAdd, CustomerToUpdate} from '../shared/customer.model';
import {WasherToUpdate} from '../../washers/shared/washer.model';

@Component({
  selector: 'app-customer-detail',
  templateUrl: './customer-detail.component.html',
  styleUrls: ['./customer-detail.component.css']
})
export class CustomerDetailComponent implements OnInit {

  public id: number;
  public firstName: string;
  public lastName: string;
  public phoneNumber: string;
  public credit: string;
  public genderId: string;

  public isEditingMode = false;

  constructor(
    private customerService: CustomerService,
    private snackBar: MatSnackBar,
    private router: Router,
    private activatedRoute: ActivatedRoute
  ) { }

  ngOnInit() {
    const customerId = this.activatedRoute.snapshot.paramMap.get('id');
    if (Number(customerId) > 0) {
      this.id = this.customerService.currentCustomer.id;
      this.firstName = this.customerService.currentCustomer.firstName;
      this.lastName = this.customerService.currentCustomer.lastName;
      this.phoneNumber = this.customerService.currentCustomer.phoneNumber;
      this.credit = this.customerService.currentCustomer.credit;
      this.genderId = this.customerService.currentCustomer.genderId;
    } else if (Number(customerId) === -1) {
      this.isEditingMode = true;
    }
  }
  onEditClick(target) {
    this.isEditingMode = true;
  }
  onSaveClick(target) {
    if (!this.isEditingMode) {
      const customer = new CustomerToAdd(this.lastName + this.firstName, this.lastName,
        this.firstName, this.phoneNumber, 0, this.credit);
      this.customerService.addCustomer(customer).subscribe(result => {
        if (result) {
          this.openSnackBar('添加成功！', '');
          this.router.navigate(['customers']);
        } else {
          this.openSnackBar('添加错误！', '');
        }
      }, result => {
        this.openSnackBar('添加失败！', '');
      }, () => {
        this.isEditingMode = false;
      });
    } else if (this.isEditingMode) {
      const customer = new CustomerToUpdate(this.id, this.lastName + this.firstName, this.firstName, this.lastName,
        this.phoneNumber, this.genderId);
      this.customerService.updateCustomer(customer).subscribe(result => {
          if (result) {
            this.openSnackBar('更新成功！', '');
            this.router.navigate(['customers']);
          } else {
            this.openSnackBar('更新错误！', '');
          }
        }, result => {
          this.openSnackBar('更新失败！', '');
        },
        () => {
          this.isEditingMode = false;
        });
    }
  }
  openSnackBar(message: string, action: string) {
    this.snackBar.open(message, action, {
      duration: 2000
    });
  }
}
